package com.erf.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.erf.domain.Order;
import com.erf.domain.User;
import com.erf.mapper.OrderMapper;
import com.erf.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class ProviderController {
    @Value("${server.port}")
    private String port;

    @GetMapping("/order")
    public String order() {
        return "你获取到了端口：" + port + "的订单";
    }

    @GetMapping("/index")
    public String index() {
        try {
            Thread.sleep(100);
        } catch (Exception e) {
        }
        return port;
    }

    @GetMapping("/list")
    public String list() {
        return "list";
    }

    @GetMapping("/hot")
    @SentinelResource("hot")
    public String hot(@RequestParam(value = "num1", required = false) Integer num1, @RequestParam(value = "num2", required = false) Integer num2) {
        return num1 + "_" + num2;
    }

    /**
     * value属性定义资源名，entryType区分入口还是出口。
     * blockHandler和fallback的区别很重要，blockHandler处理BlockException，比如流量控制导致的拒绝，而fallback处理业务异常。
     * 注意事项：部分需要强调blockHandler和fallback的调用条件，比如只有在抛出异常或触发流控时才会调用
     *
     * **blockHandler**：处理 Sentinel 规则触发的流控（如 BlockException）。方法参数需与原始方法一致，可额外添加 BlockException 参数。
     * **fallback**：处理业务逻辑抛出的其他异常（如 NullPointerException）。方法参数需与原始方法一致，必须包含 Throwable 参数。
     */
    @GetMapping("/tResource")
    @SentinelResource(value = "testResource", blockHandler = "handleBlock", fallback = "handleFallback")
    public String test() {
        // 业务逻辑，可能抛出异常
        return "Success";
    }

    // 流控处理（BlockException 参数可选）
    public String handleBlock(BlockException ex) {
        return "Request blocked by Sentinel";
    }

    // 降级处理（需包含 Throwable 参数）
    public String handleFallback(Throwable t) {
        return "Fallback due to exception: " + t.getMessage();
    }



    @Autowired
    private UserMapper userMapper;

    /**
     * 数据库的测试方法
     *
     * @return List<User> 数据库中全部user
     */
    @RequestMapping("/allUser")
    public List<User> allUser() {
        return userMapper.selectList(null);
    }

    @Autowired
    private OrderMapper orderMapper;

    @RequestMapping("/order")
    public String getOrder(@RequestParam int id) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        Order order = orderMapper.selectOne(wrapper);
        return order == null ? "null" : order.getDescription();
    }

    @RequestMapping("/addOrder")
    public int addOrder(@RequestBody Order order){
        return orderMapper.insert(order);
    }


}
